//
//  MARegisterForgetController.m
//  meiang_edu
//
//  Created by Liubi_Chaos_G on 2018/7/30.
//  Copyright © 2018年 com.meiang.meiang_edu. All rights reserved.
//

#import "MARegisterForgetController.h"

#import "NSString+Regular.h"

@interface MARegisterForgetController ()
@property (weak, nonatomic) IBOutlet UITextField *phoneTF;
@property (weak, nonatomic) IBOutlet UITextField *codeTF;
@property (weak, nonatomic) IBOutlet UITextField *pwdTF;
@property (weak, nonatomic) IBOutlet UITextField *againPwdTF;
@property (weak, nonatomic) IBOutlet UIButton *codeBtn;
@property (weak, nonatomic) IBOutlet UIButton *submitBtn;

/** 定时器 */
@property(nonatomic,weak) NSTimer *timer;
@end

static NSInteger i_ = 59;
@implementation MARegisterForgetController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupBasic];
}

- (void)setupBasic {
    
    self.phoneTF.layer.borderColor = [UIColor whiteColor].CGColor;
    self.codeTF.layer.borderColor = [UIColor whiteColor].CGColor;
    self.pwdTF.layer.borderColor = [UIColor whiteColor].CGColor;
    self.againPwdTF.layer.borderColor = [UIColor whiteColor].CGColor;
    
    self.codeBtn.layer.cornerRadius = 5;
    self.codeBtn.layer.masksToBounds = YES;
    
    self.submitBtn.layer.cornerRadius = 4;
    self.submitBtn.layer.masksToBounds = YES;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)getCode:(UIButton *)btn {
    
    DLog(@"发送请求获取验证码");
    
    NSString *phone = self.phoneTF.text;
    if (![phone isTelephone]) {
        [MBManager showBriefAlert:@"输入的手机号码不规范"];
        return;
    }
    
    [ZBRequestManager requestWithConfig:^(ZBURLRequest *request) {
        request.requestSerializerType = ZBHTTPRequestSerializer;
        request.URLString = [NSString stringWithFormat:@"%@%@",REGISTER_SENDMSG,phone];
        request.methodType = ZBMethodTypeGET;
        request.apiType = ZBRequestTypeRefresh;
    } success:^(id responseObject, apiType type) {
        // 解析数据
        NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        DLog(@"%@",dataDict);
        NSInteger code = [dataDict[@"msgcode"] integerValue];
        if (code == 1) { // 请求成功
            
        } else {
            [MBManager showBriefAlert:dataDict[@"message"]];
        }
    } failure:^(NSError *error) {
        DLog(@"%@",error);
        [MBManager showBriefAlert:@"网络错误"];
        
    } finished:^(id responseObject, apiType type, NSError *error, BOOL isCache) {
        if (isCache==YES) {
            DLog(@"使用了缓存");
        }
    }];
    
    // 验证码的时间限制
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(changeTime:) userInfo:nil repeats:YES];
    self.timer = timer;
    // 加入运行循环
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
}

#pragma mark - 验证码的时间限制
- (void)changeTime:(NSTimer *)timer
{
    if (i_ < 0) {
        self.codeBtn.enabled = YES;
        [self.codeBtn setTitle:@"重新获取" forState:UIControlStateNormal];
        [self.timer invalidate];
        i_ = 59;
        self.timer = nil;
        return;
    }
    self.codeBtn.enabled = NO;
    [self.codeBtn setTitle:[NSString stringWithFormat:@"重新获取(%02zd)",i_--] forState:UIControlStateDisabled];
}
- (IBAction)submit {
    NSString *phone = self.phoneTF.text;
    NSString *code = self.codeTF.text;
    NSString *pwd = self.pwdTF.text;
    NSString *againPwd = self.againPwdTF.text;
    if (!phone.length || !code.length || !pwd.length || !againPwd.length) {
        [MBManager showBriefAlert:@"填写信息不完整"];
        return;
    }
    if (pwd.length < 6) {
        [MBManager showBriefAlert:@"密码长度不能低于6位"];
        return;
    }
    if (![pwd isEqualToString:againPwd]) {
        [MBManager showBriefAlert:@"两次密码输入不一致"];
        return;
    }
    if (![phone isTelephone]) {
        [MBManager showBriefAlert:@"输入的手机号码不规范"];
        return;
    }
    [MBManager showLoading];
    NSString *us_id = self.isRegister ? @"register" : @"forget";
    NSDictionary *body = @{@"telphone" : phone, @"mycode" : code, @"pwd" : pwd, @"us_id" : us_id};

    NSError *error;

    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:body options:0 error:&error];

    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

    NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:REGISTER_ADD_AAA parameters:nil error:nil];

    [req setValue:@"application/text" forHTTPHeaderField:@"Content-Type"];

    [req setValue:@"application/json" forHTTPHeaderField:@"Accept"];

    [req setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];

    [[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        [MBManager hideAlert];
        if (!error) {
            NSInteger msgcode = [responseObject[@"msgcode"] integerValue];
            NSString *message = responseObject[@"message"];
            if (msgcode == 1) {
                [MBManager showBriefAlert:message];
                [self.navigationController popViewControllerAnimated:YES];
            } else {
                [MBManager showBriefAlert:message];
            }
            DLog(@"Reply JSON: %@", responseObject);

        } else {
            DLog(@"Error: %@, %@, %@", error, response, responseObject);
            [MBManager showBriefAlert:@"网络错误"];
        }
    }] resume];
}

@end
